package com.woniuxy.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.entity.AdminUser;
import com.woniuxy.jwt.Audience;
import com.woniuxy.jwt.JwtUtil;
import com.woniuxy.mapper.AdminUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm，用于与数据库交互
 */
public class DbRealm extends AuthorizingRealm {
    @Autowired
    AdminUserMapper adminUserMapper;

    @Autowired
    private Audience audience;

    /**
     * 后台管理系统中所有管理员的权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String jwt = principalCollection.getPrimaryPrincipal().toString();
        String account = JwtUtil.getAccount(jwt,audience.getBase64Secret());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        AdminUser roleByAccount = adminUserMapper.findRoleByAccount(account);
        roleByAccount.getRoles().forEach(role -> {
            role.getPerms().forEach(perms -> {
                info.addStringPermission(perms.getCode());
            });
        });

        return info;
    }

    @Override
    protected AuthenticationInfo  doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String account = upToken.getUsername();
        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        AdminUser adminUser = adminUserMapper.selectOne(queryWrapper);
        if (adminUser == null){
            throw new UnknownAccountException("账号"+account+"不存在");
        }

        return new SimpleAuthenticationInfo(adminUser,adminUser.getPwd(),getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
